from datetime import date

from datetime import date
from decimal import Decimal

from django.contrib.auth.models import AbstractUser
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models

# Create your models here.

class User(AbstractUser):
    phone = models.CharField(max_length=11, unique=True, verbose_name='手机号',blank=True,null=True)
    verify = models.CharField(choices=(('0', '未认证'), ('1', '已认证')), default='0', max_length=255, verbose_name='是否认证')

    class Meta:
        db_table = 'tb_user'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.username}({self.phone})'
    
    def get_verify_status(self):
        """获取认证状态，如果字段不存在则返回默认值"""
        try:
            return self.verify
        except:
            return '0'  # 默认未认证


# 用户登录记录表
# class UserLoginRecord(models.Model):
#     user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
#     login_time = models.DateTimeField(auto_now_add=True, verbose_name='登录时间')
#     token = models.CharField(max_length=255, verbose_name='最后一次的登录token')
#     status = models.BooleanField(default=1, verbose_name='登录状态,是否可用')
#     electronic_device = models.IntegerField(choices=((0, '电脑端'), (1, '手机端')), default=0, verbose_name='登录设备,0:PC,1:移动端')
#
#     class Meta:
#         db_table = 'tb_user_login_record'



# 第三方登录记录表
class ThreeLogin(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='关联用户')
    plate = models.CharField(max_length=255, verbose_name='第三方平台')
    uid = models.CharField(max_length=255, verbose_name='第三方平台用户ID')
    token = models.CharField(max_length=255, verbose_name='第三方平台用户token',blank= True,null=True)
    retoken = models.CharField(max_length=255, verbose_name='第三方平台用户refresh_token',blank= True,null=True)

    class Meta:
        db_table = "tb-three-login"





# 实名认证表
class UserVerify(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='关联用户')
    image_url = models.CharField(max_length=255, verbose_name='图片地址')
    name = models.CharField(max_length=255, verbose_name='真实姓名')
    id_card = models.CharField(max_length=255, verbose_name='身份证号')

    class Meta:
        db_table = "tb_user_verify"

class UserProfile(models.Model):
    # 基本信息
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    nickname = models.CharField(max_length=50, blank=True, null=True)
    avatar = models.URLField(blank=True, null=True)
    logo_url = models.URLField(max_length=1000, blank=True, null=True, help_text="用户专属LOGO地址")

    # 个人特征
    GENDER_CHOICES = [
        ('M', '男'),
        ('F', '女'),
        ('O', '其他'),
    ]
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True)
    birth_date = models.DateField(blank=True, null=True)

    # 身体指标
    height = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        validators=[MinValueValidator(50), MaxValueValidator(250)],
        help_text="单位: 厘米",
        blank=True,
        null=True
    )
    weight = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        validators=[MinValueValidator(20), MaxValueValidator(300)],
        help_text="单位: 千克",
        blank=True,
        null=True
    )

    # 健身目标
    FITNESS_GOAL_CHOICES = [
        ('weight_loss', '减脂'),
        ('muscle_gain', '增肌'),
        ('keep_fit', '保持健康'),
        ('endurance', '提升耐力'),
    ]
    fitness_goal = models.CharField(
        max_length=20,
        choices=FITNESS_GOAL_CHOICES,
        default='keep_fit'
    )

    # 健身水平
    FITNESS_LEVEL_CHOICES = [
        ('beginner', '新手'),
        ('intermediate', '进阶'),
        ('advanced', '专业'),
    ]
    fitness_level = models.CharField(
        max_length=20,
        choices=FITNESS_LEVEL_CHOICES,
        default='beginner'
    )

    # 饮食偏好
    DIETARY_PREFERENCE_CHOICES = [
        ('regular', '普通'),
        ('vegetarian', '素食'),
        ('vegan', '纯素'),
        ('low_carb', '低碳水'),
        ('keto', '生酮'),
        ('gluten_free', '无麸质'),
        ('lactose_free', '无乳糖'),
    ]
    dietary_preference = models.CharField(
        max_length=20,
        choices=DIETARY_PREFERENCE_CHOICES,
        default='regular'
    )

    # 活动水平 (用于计算代谢率)
    ACTIVITY_LEVEL_CHOICES = [
        ('sedentary', '久坐(几乎不运动)'),
        ('light', '轻度活动(每周1-3天运动)'),
        ('moderate', '中度活动(每周3-5天运动)'),
        ('active', '积极活动(每周6-7天运动)'),
        ('very_active', '非常活跃(高强度训练或体力工作)'),
    ]
    activity_level = models.CharField(
        max_length=20,
        choices=ACTIVITY_LEVEL_CHOICES,
        default='sedentary'
    )

    # 健康相关信息
    has_diabetes = models.BooleanField(default=False)
    has_hypertension = models.BooleanField(default=False)
    has_heart_disease = models.BooleanField(default=False)
    food_allergies = models.TextField(blank=True, null=True, help_text="食物过敏信息")
    dietary_restrictions = models.TextField(blank=True, null=True, help_text="其他饮食限制")

    # 健身偏好
    preferred_workout_duration = models.PositiveIntegerField(
        default=30,
        validators=[MinValueValidator(10), MaxValueValidator(180)],
        help_text="偏好的单次训练时长(分钟)"
    )
    preferred_workout_times = models.PositiveIntegerField(
        default=3,
        validators=[MinValueValidator(1), MaxValueValidator(7)],
        help_text="每周偏好的训练次数"
    )

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    # 计算属性
    @property
    def age(self):
        """计算用户年龄"""
        if self.birth_date:
            today = date.today()
            return today.year - self.birth_date.year - (
                    (today.month, today.day) < (self.birth_date.month, self.birth_date.day)
            )
        return None

    @property
    def bmi(self):
        """计算身体质量指数(BMI)"""
        if self.height and self.weight:
            # BMI = 体重(kg) / 身高(m)^2
            height_in_m = float(self.height) / 100
            return round(float(self.weight) / (height_in_m ** 2), 1)
        return None

    @property
    def bmi_category(self):
        """根据BMI值返回分类"""
        bmi_val = self.bmi
        if not bmi_val:
            return None

        if bmi_val < 18.5:
            return "偏瘦"
        elif 18.5 <= bmi_val < 25:
            return "正常"
        elif 25 <= bmi_val < 30:
            return "超重"
        else:
            return "肥胖"

    def calculate_bmr(self):
        """计算基础代谢率(BMR) - 使用Mifflin-St Jeor公式"""
        if not all([self.height, self.weight, self.age, self.gender]):
            return None

        if self.gender == 'M':  # 男性
            bmr = 10 * float(self.weight) + 6.25 * float(self.height) - 5 * self.age + 5
        else:  # 女性或其他
            bmr = 10 * float(self.weight) + 6.25 * float(self.height) - 5 * self.age - 161

        return round(bmr)

    def calculate_tdee(self):
        """计算每日总能量消耗(TDEE)"""
        bmr = self.calculate_bmr()
        if not bmr:
            return None

        # 根据活动水平调整
        activity_multipliers = {
            'sedentary': 1.2,
            'light': 1.375,
            'moderate': 1.55,
            'active': 1.725,
            'very_active': 1.9
        }

        return round(bmr * activity_multipliers.get(self.activity_level, 1.2))

    def calculate_calorie_target(self):
        """根据健身目标计算每日卡路里目标"""
        tdee = self.calculate_tdee()
        if not tdee:
            return None

        # 根据目标调整
        if self.fitness_goal == 'weight_loss':
            return tdee - 500  # 减脂: 创造500卡路里缺口
        elif self.fitness_goal == 'muscle_gain':
            return tdee + 300  # 增肌: 创造300卡路里盈余
        else:
            return tdee  # 保持健康: 维持

    def __str__(self):
        return f"{self.user.username} - {self.get_fitness_goal_display()}"

    class Meta:
        db_table = "tb_user_profile_details"
        verbose_name = "用户详情"
        verbose_name_plural = "用户详情"

